// pages/article/article.js
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: false,
    interval: 2000,
    duration: 500,
    circular: true,
    bannerList: [], // 轮播图
    articleId: Number,
    articleData: {},
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    animationData: {},
    canvasWidth: Number,
    canvasHeight: Number,
    imageFile: '', // 保存canvas绘制的图像到临时目录
    visible: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 登录
    wx.login({
      success: res => {
        const url = 'https://www.bisaiquan.cn/api/wechat/login'
        const data = {
          code: res.code
        }
        wx.request({
          url: url,
          data: data,
          method: 'POST',
          success(response) {
            wx.setStorageSync('openToken', response.data.data.open_token)
          }
        })
      }
    })

    // 获取系统信息
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          canvasWidth: res.windowWidth - 60,
          canvasHeight: res.windowHeight - 120
        })
      },
    })

    const id = parseInt(options.wthread_id)
    this.setData({
      articleId: id
    })
  },
  // 获取文章详情
  getArticle: function (id) {
    const _this = this
    const url = 'content/thread'
    const data = {
      wthread_id: id
    }
    app.$http.post(url, data).then(res => {
      _this.setData({
        articleData: res.data
      })
      wx.setNavigationBarTitle({
        title: res.data.title,
      })
    })
  },
  // 显示遮罩层
  showModal: function () {
    var that = this
    that.setData({
      hideModal: false
    })
    var animation = wx.createAnimation({
      duration: 100, //动画的持续时间 默认600ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn() //调用显示动画
    }, 100)
  },

  // 隐藏遮罩层
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 100, //动画的持续时间 默认800ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease', //动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown() //调用隐藏动画   
    setTimeout(function () {
      that.setData({
        hideModal: true
      })
    }, 120) //先执行下滑动画，再隐藏模块
  },
  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(240).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },
  // 生成海报相关 - 获取网络路径图片，调用微信api，wx.getImageInfo，进行Promise化
  getImageInfo: function (url) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: url,
        success: resolve,
        fail: reject,
      })
    })
  },
  // 保存canvas绘制的图像到临时目录，调用微信小程序api，wx.canvasToTempFilePath，进行Promise化
  canvasToTempFilePath: function (option, context) {
    return new Promise((resolve, reject) => {
      wx.canvasToTempFilePath({
        ...option,
        success: resolve,
        fail: reject,
      }, context)
    })
  },
  // 保存图片到相册需要调用微信小程序api，wx.saveImageToPhotosAlbum，进行Promise化
  saveImageToPhotosAlbum: function (option) {
    return new Promise((resolve, reject) => {
      wx.saveImageToPhotosAlbum({
        ...option,
        success: resolve,
        fail: reject,
      })
    })
  },
  // 保存图片到相册
  handleSave(imageFile) {
    const _this = this
    if (imageFile) {
      _this.saveImageToPhotosAlbum({
        filePath: imageFile,
      }).then(() => {
        wx.showToast({
          icon: 'none',
          title: '分享图片已保存至相册，快去分享朋友圈吧!',
          duration: 3000,
          success: () => {
            _this.setData({
              visible: false
            })
          }
        })
      }).catch(() => {
        wx.showToast({
          title: '保存失败!',
          icon: 'none'
        })
      })
    }
  },
  // 生成小程序码
  getMiniProgramQrcode: function () {
    const _this = this
    const url = 'wechat/wxacode'
    const data = {
      page: '/pages/article/article',
      id: this.data.articleId
    }
    app.$http.post(url, data).then(res => {
      console.log(res)
    })
  },
  // 生成canvas海报
  canvasDraw: function () {
    const _this = this
    wx.showLoading({
      title: '绘制中...',
    })
    this.setData({
      visible: true
    })
    const nickName = '淮海魔方'

    // 获取头像图像信息
    const avatar = '../../static/avatar.png'
    // const avatarPromise = this.getImageInfo('https://huhaicube.oss-cn-hangzhou.aliyuncs.com/2020/06/18/icon/oss2020061807423135e425778d0dc11c5c0e6a413bf1efca6iq.jpg')
    // 获取背景图像信息
    // const backgroundPromise = this.getImageInfo('https://img.xiaomeipingou.com/_assets_home-share-bg.jpg')
    // const background = '../../static/shareBg.png'

    // Promise.all([avatarPromise, backgroundPromise])
    // .then(([avatar, background]) => {
    // 创建绘图上下文
    const ctx = wx.createCanvasContext('share', this)

    const canvasWidth = this.data.canvasWidth
    const canvasHeight = this.data.canvasHeight
    // 绘制背景，填充满整个canvas画布
    // ctx.drawImage(background, 0, 0, canvasWidth, canvasHeight)
    ctx.setFillStyle('white')
    ctx.fillRect(0, 0, canvasWidth, canvasHeight)

    const avatarWidth = 60
    const avatarHeight = 60
    const avatarTop = 80
    // 绘制头像
    ctx.drawImage(
      avatar,
      // avatarPromise,
      canvasWidth / 2 - avatarWidth / 2,
      avatarTop - avatarHeight / 2,
      avatarWidth,
      avatarHeight
    )

    // 绘制用户名
    ctx.setFontSize(20)
    ctx.setTextAlign('center')
    ctx.setFillStyle('#000000')
    ctx.fillText(
      nickName,
      canvasWidth / 2,
      avatarTop + 50,
    )
    ctx.stroke()
    // 完成作画
    // ctx.draw()
    ctx.draw(false, () => {
      wx.hideLoading({
        success: () => {
          _this.canvasToTempFilePath({
            canvasId: 'share',
          }, this).then(res => {
            _this.handleSave(res.tempFilePath)
          })
        }
      })

    })
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getArticle(this.data.articleId)
    this.getMiniProgramQrcode(this.data.articleId)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})